import React, { useState } from 'react';
import {
  usePerformanceMonitor,
  usePerformanceReport,
  useMemoryMonitor,
  PerformanceMetrics,
  PerformanceReport,
} from '../hooks/usePerformance';
import {
  ChartBarIcon,
  CpuChipIcon,
  CircleStackIcon,
  ClockIcon,
  ExclamationTriangleIcon,
  ArrowPathIcon,
} from '@heroicons/react/24/outline';
import { clsx } from 'clsx';

interface PerformanceMonitorProps {
  className?: string;
  showDetails?: boolean;
  autoRefresh?: boolean;
  refreshInterval?: number;
}

export const PerformanceMonitor: React.FC<PerformanceMonitorProps> = ({
  className,
  showDetails = false,
  autoRefresh = true,
  refreshInterval = 5000,
}) => {
  const [showReport, setShowReport] = useState(false);

  const {
    metrics,
    history,
    isMonitoring,
    error,
    startMonitoring,
    stopMonitoring,
    collectMetrics,
  } = usePerformanceMonitor({
    autoStart: autoRefresh,
    interval: refreshInterval,
  });

  const {
    report,
    loading: reportLoading,
    generateReport,
  } = usePerformanceReport();

  const { memoryWarning, memoryPercentage } = useMemoryMonitor();

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatDuration = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;

    if (hours > 0) {
      return `${hours}h ${minutes}m ${secs}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${secs}s`;
    } else {
      return `${secs}s`;
    }
  };

  const getPerformanceStatus = (metrics: PerformanceMetrics) => {
    if (metrics.cpu_usage > 80 || memoryPercentage > 80) {
      return {
        status: 'critical',
        color: 'text-red-600',
        bgColor: 'bg-red-50',
      };
    } else if (metrics.cpu_usage > 60 || memoryPercentage > 60) {
      return {
        status: 'warning',
        color: 'text-yellow-600',
        bgColor: 'bg-yellow-50',
      };
    } else {
      return {
        status: 'good',
        color: 'text-green-600',
        bgColor: 'bg-green-50',
      };
    }
  };

  // 显示错误信息
  if (error) {
    return (
      <div
        className={clsx(
          'rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-800 dark:bg-red-900/20',
          className
        )}
      >
        <div className="flex items-center">
          <ExclamationTriangleIcon className="mr-2 h-5 w-5 text-red-500" />
          <div>
            <div className="font-medium text-red-800 dark:text-red-200">
              性能数据加载失败
            </div>
            <div className="mt-1 text-sm text-red-600 dark:text-red-400">
              {error}
            </div>
            <button
              onClick={() => collectMetrics()}
              className="mt-2 rounded bg-red-100 px-3 py-1 text-sm text-red-800 hover:bg-red-200 dark:bg-red-800 dark:text-red-200 dark:hover:bg-red-700"
            >
              重试
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (!metrics) {
    return (
      <div
        className={clsx(
          'rounded-lg bg-gray-50 p-4 dark:bg-gray-800',
          className
        )}
      >
        <div className="flex items-center justify-center">
          <ArrowPathIcon className="mr-2 h-5 w-5 animate-spin" />
          <span>加载性能数据...</span>
        </div>
      </div>
    );
  }

  const performanceStatus = getPerformanceStatus(metrics);

  return (
    <div className={clsx('space-y-4', className)}>
      {/* 性能概览 */}
      <div
        className={clsx(
          'rounded-lg border p-4',
          performanceStatus.bgColor,
          'border-gray-200 dark:border-gray-700'
        )}
      >
        <div className="mb-4 flex items-center justify-between">
          <h3 className="flex items-center text-lg font-semibold">
            <ChartBarIcon className="mr-2 h-5 w-5" />
            性能监控
          </h3>

          <div className="flex items-center space-x-2">
            {memoryWarning && (
              <ExclamationTriangleIcon
                className="h-5 w-5 text-red-500"
                title="内存使用过高"
              />
            )}

            <button
              onClick={isMonitoring ? stopMonitoring : startMonitoring}
              className={clsx(
                'rounded px-3 py-1 text-sm font-medium',
                isMonitoring
                  ? 'bg-red-100 text-red-700 hover:bg-red-200'
                  : 'bg-green-100 text-green-700 hover:bg-green-200'
              )}
            >
              {isMonitoring ? '停止监控' : '开始监控'}
            </button>

            <button
              onClick={() => collectMetrics()}
              className="rounded bg-blue-100 px-3 py-1 text-sm font-medium text-blue-700 hover:bg-blue-200"
              title="手动刷新性能数据"
            >
              <ArrowPathIcon className="h-4 w-4" />
            </button>
          </div>
        </div>

        {/* 关键指标 */}
        <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
          <div className="flex items-center">
            <CpuChipIcon className="mr-3 h-8 w-8 text-blue-500" />
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                CPU 使用率
              </div>
              <div className="text-lg font-semibold">
                {metrics.cpu_usage.toFixed(1)}%
              </div>
            </div>
          </div>

          <div className="flex items-center">
            <CircleStackIcon className="mr-3 h-8 w-8 text-green-500" />
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                内存使用
              </div>
              <div className="text-lg font-semibold">
                {formatBytes(metrics.memory_usage)}
              </div>
              <div className="text-xs text-gray-500">
                {memoryPercentage.toFixed(1)}%
              </div>
            </div>
          </div>

          <div className="flex items-center">
            <ClockIcon className="mr-3 h-8 w-8 text-purple-500" />
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                运行时间
              </div>
              <div className="text-lg font-semibold">
                {formatDuration(metrics.uptime)}
              </div>
            </div>
          </div>

          <div className="flex items-center">
            <ChartBarIcon className="mr-3 h-8 w-8 text-orange-500" />
            <div>
              <div className="text-sm text-gray-600 dark:text-gray-400">
                进程数
              </div>
              <div className="text-lg font-semibold">
                {metrics.process_count}
              </div>
            </div>
          </div>
        </div>

        {/* 自定义指标 */}
        {Object.keys(metrics.custom_metrics).length > 0 && (
          <div className="mt-4 border-t border-gray-200 pt-4 dark:border-gray-600">
            <h4 className="mb-2 text-sm font-medium">自定义指标</h4>
            <div className="grid grid-cols-2 gap-2 md:grid-cols-4">
              {Object.entries(metrics.custom_metrics).map(([key, value]) => (
                <div key={key} className="text-sm">
                  <span className="text-gray-600 dark:text-gray-400">
                    {key}:
                  </span>
                  <span className="ml-1 font-medium">{value.toFixed(2)}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* 详细信息 */}
      {showDetails && (
        <div className="space-y-4">
          {/* 历史图表 */}
          <div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
            <div className="mb-4 flex items-center justify-between">
              <h4 className="text-lg font-semibold">性能趋势</h4>
              <div className="text-sm text-gray-500 dark:text-gray-400">
                数据点: {history.length} | 监控状态:{' '}
                {isMonitoring ? '运行中' : '已停止'}
              </div>
            </div>
            {history.length > 0 ? (
              <div>
                <PerformanceStats data={history} />
                <PerformanceChart data={history} />
              </div>
            ) : (
              <div className="flex h-32 items-center justify-center rounded bg-gray-50 dark:bg-gray-700">
                <div className="text-center text-gray-500 dark:text-gray-400">
                  <ChartBarIcon className="mx-auto mb-2 h-8 w-8" />
                  <div>暂无性能数据</div>
                  <div className="mt-1 text-xs">
                    {isMonitoring
                      ? '正在收集数据...'
                      : '点击开始监控按钮开始收集数据'}
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* 性能报告 */}
          <div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
            <div className="mb-4 flex items-center justify-between">
              <h4 className="text-lg font-semibold">性能报告</h4>
              <button
                onClick={generateReport}
                disabled={reportLoading}
                className="rounded bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 disabled:opacity-50"
              >
                {reportLoading ? '生成中...' : '生成报告'}
              </button>
            </div>

            {report && <PerformanceReportView report={report} />}
          </div>
        </div>
      )}

      {/* 控制按钮 */}
      <div className="flex justify-center">
        <button
          onClick={() => setShowReport(!showReport)}
          className="text-sm font-medium text-blue-600 hover:text-blue-800"
        >
          {showDetails ? '隐藏详细信息' : '显示详细信息'}
        </button>
      </div>
    </div>
  );
};

// 性能统计摘要组件
const PerformanceStats: React.FC<{ data: PerformanceMetrics[] }> = ({
  data,
}) => {
  if (!data || data.length === 0) return null;

  const stats = {
    avgCpu: data.reduce((sum, d) => sum + d.cpu_usage, 0) / data.length,
    maxCpu: Math.max(...data.map(d => d.cpu_usage)),
    avgMemory: data.reduce((sum, d) => sum + d.memory_usage, 0) / data.length,
    maxMemory: Math.max(...data.map(d => d.memory_usage)),
    dataPoints: data.length,
    timeSpan:
      data.length > 1 ? data[data.length - 1].timestamp - data[0].timestamp : 0,
  };

  return (
    <div className="mb-4 grid grid-cols-2 gap-4 md:grid-cols-4">
      <div className="rounded-lg bg-blue-50 p-3 dark:bg-blue-900/20">
        <div className="text-sm text-blue-600 dark:text-blue-400">平均 CPU</div>
        <div className="text-lg font-semibold text-blue-800 dark:text-blue-200">
          {stats.avgCpu.toFixed(1)}%
        </div>
      </div>
      <div className="rounded-lg bg-red-50 p-3 dark:bg-red-900/20">
        <div className="text-sm text-red-600 dark:text-red-400">峰值 CPU</div>
        <div className="text-lg font-semibold text-red-800 dark:text-red-200">
          {stats.maxCpu.toFixed(1)}%
        </div>
      </div>
      <div className="rounded-lg bg-green-50 p-3 dark:bg-green-900/20">
        <div className="text-sm text-green-600 dark:text-green-400">
          平均内存
        </div>
        <div className="text-lg font-semibold text-green-800 dark:text-green-200">
          {(stats.avgMemory / 1024 / 1024).toFixed(1)}MB
        </div>
      </div>
      <div className="rounded-lg bg-purple-50 p-3 dark:bg-purple-900/20">
        <div className="text-sm text-purple-600 dark:text-purple-400">
          峰值内存
        </div>
        <div className="text-lg font-semibold text-purple-800 dark:text-purple-200">
          {(stats.maxMemory / 1024 / 1024).toFixed(1)}MB
        </div>
      </div>
    </div>
  );
};

// SVG曲线图组件
const PerformanceChart: React.FC<{ data: PerformanceMetrics[] }> = ({
  data,
}) => {
  if (!data || data.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center rounded bg-gray-50 dark:bg-gray-700">
        <div className="text-gray-500 dark:text-gray-400">暂无数据</div>
      </div>
    );
  }

  // 显示最近50个数据点，获得更好的曲线效果
  const displayData = data.slice(-50);

  // 如果只有一个数据点，创建一些模拟数据来显示基本线条
  const chartData =
    displayData.length === 1
      ? [
          { ...displayData[0], timestamp: displayData[0].timestamp - 60 },
          displayData[0],
          { ...displayData[0], timestamp: displayData[0].timestamp + 60 },
        ]
      : displayData;

  const maxCpu = Math.max(...chartData.map(d => d.cpu_usage), 1);
  const maxMemory = Math.max(...chartData.map(d => d.memory_usage), 1);
  const minCpu = Math.min(...chartData.map(d => d.cpu_usage), 0);
  const minMemory = Math.min(...chartData.map(d => d.memory_usage), 0);

  // SVG 尺寸
  const width = 800;
  const height = 200;
  const padding = { top: 20, right: 20, bottom: 40, left: 60 };
  const chartWidth = width - padding.left - padding.right;
  const chartHeight = height - padding.top - padding.bottom;

  // 创建平滑曲线路径
  const createSmoothPath = (
    values: number[],
    maxValue: number,
    minValue: number
  ) => {
    if (chartData.length < 2) return '';

    const points = chartData.map((_, index) => ({
      x: (index / (chartData.length - 1)) * chartWidth,
      y:
        chartHeight -
        ((values[index] - minValue) / (maxValue - minValue)) * chartHeight,
    }));

    let path = `M ${points[0].x} ${points[0].y}`;

    for (let i = 1; i < points.length; i++) {
      const prev = points[i - 1];
      const curr = points[i];
      const next = points[i + 1];

      if (i === 1) {
        // 第一个控制点
        const cp1x = prev.x + (curr.x - prev.x) * 0.3;
        const cp1y = prev.y;
        const cp2x = curr.x - (curr.x - prev.x) * 0.3;
        const cp2y = curr.y;
        path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`;
      } else if (i === points.length - 1) {
        // 最后一个控制点
        const cp1x = prev.x + (curr.x - prev.x) * 0.3;
        const cp1y = prev.y;
        const cp2x = curr.x - (curr.x - prev.x) * 0.3;
        const cp2y = curr.y;
        path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`;
      } else {
        // 中间的控制点
        const cp1x = prev.x + (curr.x - prev.x) * 0.3;
        const cp1y = prev.y + (curr.y - prev.y) * 0.3;
        const cp2x = curr.x - (next.x - prev.x) * 0.1;
        const cp2y = curr.y - (next.y - prev.y) * 0.1;
        path += ` C ${cp1x} ${cp1y}, ${cp2x} ${cp2y}, ${curr.x} ${curr.y}`;
      }
    }

    return path;
  };

  const cpuValues = chartData.map(d => d.cpu_usage);
  const memoryValues = chartData.map(d => d.memory_usage / 1024 / 1024); // 转换为MB

  const cpuPath = createSmoothPath(cpuValues, maxCpu, minCpu);
  const memoryPath = createSmoothPath(
    memoryValues,
    maxMemory / 1024 / 1024,
    minMemory / 1024 / 1024
  );

  return (
    <div className="space-y-4">
      {/* 图例 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-6 text-sm">
          <div className="flex items-center">
            <div className="mr-2 h-3 w-3 rounded bg-blue-500"></div>
            <span>
              CPU 使用率 ({minCpu.toFixed(1)}% - {maxCpu.toFixed(1)}%)
            </span>
          </div>
          <div className="flex items-center">
            <div className="mr-2 h-3 w-3 rounded bg-green-500"></div>
            <span>
              内存使用 ({(minMemory / 1024 / 1024).toFixed(1)}MB -{' '}
              {(maxMemory / 1024 / 1024).toFixed(1)}MB)
            </span>
          </div>
        </div>
        <div className="text-xs text-gray-500 dark:text-gray-400">
          数据点: {chartData.length}
        </div>
      </div>

      {/* SVG 曲线图 */}
      <div className="rounded-lg border border-gray-200 bg-white p-4 dark:border-gray-700 dark:bg-gray-800">
        <svg
          width="100%"
          height="240"
          viewBox={`0 0 ${width} ${height + 40}`}
          className="overflow-visible"
        >
          {/* 网格线 */}
          <defs>
            <pattern
              id="grid"
              width="40"
              height="20"
              patternUnits="userSpaceOnUse"
            >
              <path
                d="M 40 0 L 0 0 0 20"
                fill="none"
                stroke="#e5e7eb"
                strokeWidth="0.5"
                opacity="0.5"
              />
            </pattern>
          </defs>
          <rect
            x={padding.left}
            y={padding.top}
            width={chartWidth}
            height={chartHeight}
            fill="url(#grid)"
          />

          {/* Y轴标签 - CPU */}
          <g transform={`translate(${padding.left - 10}, ${padding.top})`}>
            <text
              x="0"
              y="0"
              textAnchor="end"
              className="fill-blue-600 text-xs dark:fill-blue-400"
              dy="0.3em"
            >
              {maxCpu.toFixed(0)}%
            </text>
            <text
              x="0"
              y={chartHeight / 2}
              textAnchor="end"
              className="fill-blue-600 text-xs dark:fill-blue-400"
              dy="0.3em"
            >
              {((maxCpu + minCpu) / 2).toFixed(0)}%
            </text>
            <text
              x="0"
              y={chartHeight}
              textAnchor="end"
              className="fill-blue-600 text-xs dark:fill-blue-400"
              dy="0.3em"
            >
              {minCpu.toFixed(0)}%
            </text>
          </g>

          {/* Y轴标签 - 内存 */}
          <g
            transform={`translate(${width - padding.right + 10}, ${padding.top})`}
          >
            <text
              x="0"
              y="0"
              textAnchor="start"
              className="fill-green-600 text-xs dark:fill-green-400"
              dy="0.3em"
            >
              {(maxMemory / 1024 / 1024).toFixed(0)}MB
            </text>
            <text
              x="0"
              y={chartHeight / 2}
              textAnchor="start"
              className="fill-green-600 text-xs dark:fill-green-400"
              dy="0.3em"
            >
              {((maxMemory + minMemory) / 2 / 1024 / 1024).toFixed(0)}MB
            </text>
            <text
              x="0"
              y={chartHeight}
              textAnchor="start"
              className="fill-green-600 text-xs dark:fill-green-400"
              dy="0.3em"
            >
              {(minMemory / 1024 / 1024).toFixed(0)}MB
            </text>
          </g>

          {/* 图表区域 */}
          <g transform={`translate(${padding.left}, ${padding.top})`}>
            {/* CPU 曲线 */}
            <path
              d={cpuPath}
              fill="none"
              stroke="#3b82f6"
              strokeWidth="2"
              className="drop-shadow-sm"
            />

            {/* 内存曲线 */}
            <path
              d={memoryPath}
              fill="none"
              stroke="#10b981"
              strokeWidth="2"
              className="drop-shadow-sm"
            />

            {/* 数据点 */}
            {chartData.map((metric, index) => {
              const x = (index / (chartData.length - 1)) * chartWidth;
              const cpuY =
                chartHeight -
                ((metric.cpu_usage - minCpu) / (maxCpu - minCpu)) * chartHeight;
              const memoryY =
                chartHeight -
                ((metric.memory_usage / 1024 / 1024 - minMemory / 1024 / 1024) /
                  (maxMemory / 1024 / 1024 - minMemory / 1024 / 1024)) *
                  chartHeight;

              return (
                <g key={`${metric.timestamp}-${index}`}>
                  {/* CPU 数据点 */}
                  <circle
                    cx={x}
                    cy={cpuY}
                    r="3"
                    fill="#3b82f6"
                    className="hover:r-4 cursor-pointer transition-all"
                  >
                    <title>
                      {`时间: ${new Date(metric.timestamp * 1000).toLocaleTimeString()}\nCPU: ${metric.cpu_usage.toFixed(1)}%`}
                    </title>
                  </circle>

                  {/* 内存数据点 */}
                  <circle
                    cx={x}
                    cy={memoryY}
                    r="3"
                    fill="#10b981"
                    className="hover:r-4 cursor-pointer transition-all"
                  >
                    <title>
                      {`时间: ${new Date(metric.timestamp * 1000).toLocaleTimeString()}\n内存: ${(metric.memory_usage / 1024 / 1024).toFixed(1)}MB`}
                    </title>
                  </circle>
                </g>
              );
            })}
          </g>

          {/* X轴时间标签 */}
          {chartData.length > 1 && (
            <g
              transform={`translate(${padding.left}, ${height - padding.bottom + 20})`}
            >
              <text
                x="0"
                y="0"
                textAnchor="start"
                className="fill-gray-500 text-xs dark:fill-gray-400"
              >
                {new Date(chartData[0].timestamp * 1000).toLocaleTimeString()}
              </text>
              <text
                x={chartWidth / 2}
                y="0"
                textAnchor="middle"
                className="fill-gray-500 text-xs dark:fill-gray-400"
              >
                {new Date(
                  chartData[Math.floor(chartData.length / 2)].timestamp * 1000
                ).toLocaleTimeString()}
              </text>
              <text
                x={chartWidth}
                y="0"
                textAnchor="end"
                className="fill-gray-500 text-xs dark:fill-gray-400"
              >
                {new Date(
                  chartData[chartData.length - 1].timestamp * 1000
                ).toLocaleTimeString()}
              </text>
            </g>
          )}
        </svg>
      </div>
    </div>
  );
};

// 性能报告视图组件
const PerformanceReportView: React.FC<{ report: PerformanceReport }> = ({
  report,
}) => {
  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            平均 CPU
          </div>
          <div className="text-lg font-semibold">
            {report.avg_cpu_usage.toFixed(1)}%
          </div>
        </div>
        <div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            平均内存
          </div>
          <div className="text-lg font-semibold">
            {(report.avg_memory_usage / 1024 / 1024).toFixed(1)}MB
          </div>
        </div>
        <div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            总事件数
          </div>
          <div className="text-lg font-semibold">{report.total_events}</div>
        </div>
        <div>
          <div className="text-sm text-gray-600 dark:text-gray-400">
            活跃事件
          </div>
          <div className="text-lg font-semibold">
            {report.active_events_count}
          </div>
        </div>
      </div>

      {Object.keys(report.event_stats).length > 0 && (
        <div>
          <h5 className="mb-2 font-medium">事件统计</h5>
          <div className="space-y-2">
            {Object.entries(report.event_stats).map(([name, stats]) => (
              <div
                key={name}
                className="flex items-center justify-between text-sm"
              >
                <span>{name}</span>
                <span className="text-gray-600 dark:text-gray-400">
                  {stats.count} 次, 平均 {stats.avg_duration.toFixed(1)}ms
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default PerformanceMonitor;
